#include "graphicsitem.h"


GraphicsItem::GraphicsItem(int id, const QPixmap &pixmap, QGraphicsItem *parent)
    :QGraphicsPixmapItem(pixmap, parent)
{
    recordId = id;
    setAcceptHoverEvents(true);

    timeLine.setDuration(150);
    timeLine.setFrameRange(0, 150);


    connect(&timeLine, &QTimeLine::frameChanged, this, &GraphicsItem::setFrame);
    connect(&timeLine, &QTimeLine::finished, this, &GraphicsItem::updateItemPosition);

    adjust();
}

//! [1]
void GraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent * /*event*/)
{
    timeLine.setDirection(QTimeLine::Forward);

    if (z != 1.0) {
        z = 1.0;
        updateItemPosition();
    }

    if (timeLine.state() == QTimeLine::NotRunning){
        timeLine.start();
    }
}
//! [1]

//! [2]
void GraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent * /*event*/)
{
    timeLine.setDirection(QTimeLine::Backward);
    if (z != 0.0){
        z = 0.0;
    }

    if (timeLine.state() == QTimeLine::NotRunning){
        timeLine.start();
    }
}

void GraphicsItem::setFrame(int frame)
{
    adjust();
    QPointF center = boundingRect().center();

    setTransform(QTransform::fromTranslate(center.x(), center.y()), true);
    setTransform(QTransform::fromScale(1 + frame / 330.0, 1 + frame / 330.0), true);
    setTransform(QTransform::fromTranslate(-center.x(), -center.y()), true);
}

void GraphicsItem::updateItemPosition()
{
    setZValue(z);
}

void GraphicsItem::adjust()
{
    QMatrix matrix;
    matrix.scale(120/ boundingRect().width(), 120/ boundingRect().height());
    setMatrix(matrix);
}

int GraphicsItem::id() const
{
    return recordId;
}
